#include "HttpLoader.h"
#include "MyTileSources.h"
#include <QList>
QList<QNetworkAccessManager*> managerList;
HttpLoader::HttpLoader(QObject * parent):QObject(parent)
{
	m_isReady = true; m_source = NULL; m_tilekey;
	
}

HttpLoader::~HttpLoader()
{
	delete m_file;
	m_file = NULL;
}

void HttpLoader::SetTileSource(MyTileSources * tilesoure)
{
	m_source = tilesoure;
}

void HttpLoader::downloadFileFromURL(const QString &url, const QString &filePath)
{
	if (!m_isReady)
		return;
	m_isReady = false;
	m_strPath = filePath;
	m_file = new QFile();
	m_file->setFileName(filePath);
	m_file->open(QIODevice::WriteOnly);
	if (!m_file->isOpen()) {
		m_isReady = true;
		return;
	}
	//shared_ptr<HttpLoader> ptrloader(new HttpLoader());

	m_pmanager= std::make_shared<QNetworkAccessManager>();// std::make_shared<int>(20)

	pmanager = new QNetworkAccessManager();
	if (managerList.size()>100)
	{
		QNetworkAccessManager* item = managerList.at(0);
		
		managerList.removeAt(0);
		delete item;
		item = NULL;
	}
	managerList.push_back(pmanager);
	QNetworkRequest request;
	request.setUrl(QUrl(url));

	connect(pmanager, SIGNAL(finished(QNetworkReply *)), this, SLOT(onDownloadFileComplete(QNetworkReply *)));
	pmanager->get(request);
}




void HttpLoader::onDownloadFileComplete(QNetworkReply *reply)
{
	if (!m_file->isWritable()) {
		m_isReady = true;
		return;
	}
	m_file->write(reply->readAll());
	m_file->close();
	m_isReady = true;
	
	if (m_source!=NULL)
	{
		m_source->slot_returResult(this, m_strPath);
	}
  // emit sig_test();
  // emit sig_ReturResult(this,m_strPath);
}
